<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class UserRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $user = Auth::User();
        $userId = $this->route('user');
        if (!empty($userId)) {
            if (!$user->can('update', new User())) {
                abort(403, '此操作未经授权.');
            }
        } else {
            if (!$user->can('store', new User())) {
                abort(403, '此操作未经授权.');
            }
        }
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $userId = $this->route('user');
        if (!empty($userId)) {
            if ($this->method() === 'PUT') {
                return [
                    'name' => 'required',
                    'mobile' => 'required|unique:users,mobile,' . $userId . ',_id|regex:/^1[0-9]{10}$/',
                    'email' => 'sometimes|unique:users,email,' . $userId . ',_id|email',
                    'group_id' => 'required',
                    'isManager' => "required",
                    'role_id' => "required",
                ];
            } else {
                return [
                    'status' => 'required',
                ];
            }
        } else {
            return [
                'name' => 'required',
                'mobile' => 'required|unique:users|regex:/^1[0-9]{10}$/',
                'email' => 'email|unique:users',
                'group_id' => 'required',
                'isManager' => "required",
                'role_id' => "required"
            ];
        }
    }
}
